package net.ibizsys.eclipse.studio.api;

import java.util.ArrayList;
import java.util.List;

import net.ibizsys.eclipse.studio.data.IBizData;
import net.ibizsys.eclipse.studio.i18n.I18n;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class ActionResult<T> extends CallResult
{
	private T data;
	private List<T> items = new ArrayList<T>();

	public ActionResult(int code, String info)
	{
		super(code, info);
	}

	public ActionResult(Class<T> t, String jsonString)
	{
		try
		{
			this.setContent(jsonString);

			JSONObject json = JSONObject.parseObject(jsonString);

			JSONObject jsonItem = json.getJSONObject("data");
			JSONArray jsonArr = json.getJSONArray("items");

			this.setRetcode(json.getIntValue("ret"));
			this.setErrorInfo(json.getString("errorMessage"));

			if (jsonItem != null)
			{
				this.data = (T) t.newInstance();

				if (this.data instanceof IBizData)
				{
					((IBizData) this.data).init(jsonItem);
				}
			}
			if (jsonArr != null)
			{
				for (int i = 0; i < jsonArr.size(); i++)
				{
					T data = (T) t.newInstance();

					if (data instanceof IBizData)
					{
						((IBizData) data).init(jsonArr.getJSONObject(i));
					}
					this.items.add(data);
				}
			}

		} catch (Exception ex)
		{
			this.setRetcode(-1);
			this.setErrorInfo(I18n.HttpDataParseError);
		}
	}

	public T getData()
	{
		return data;
	}

	public List<T> getItems()
	{
		return items;
	}
}
